<?php


namespace app\manage\controller;

use app\common\controller\BaiduService;
use app\common\controller\TengxunService;
use app\common\controller\JuliangService;
use think\Db;
use think\Log;

class Page extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    private $landingpage_type_arr = [1 => "建站", 2 => "自开发"];

    public function index()
    {
        $pro_name = input('pro_name','');
        $ac_name = input('ac_name','');
        $adv_id = input('adv_id','');

        $map = [];
        if($pro_name != ''){
            $products = Db::name('product')->field('id')->where(['name'=>['like','%'.$pro_name.'%']])->select();
            $pro_id_list = array_column($products, 'id');
            $map['pro_id'] = ['in',$pro_id_list];
        }

        if($this->group_id==7){
            $accList=model('Account')->where('bind_youhua',$this->uid)->select();
            if(empty($accList)){
                $map['id']=0;
            }else{
                $accIdArr=array_column($accList,'id');
                $map['acc_id']=['in',$accIdArr];
            }
            $Account = $accList;
        }else{
            $Account = model('Account')->getListByMap();
        }

        if (!empty($ac_name)) {
            $adv_idArr = model('Account')->where('acc_name', 'like', '%' . $ac_name . '%')->column('id');
            if (!empty($adv_idArr)) {
                $map['acc_id'] = ['in', $adv_idArr];
            } else {
                $map['acc_id'] = 0;
            }
        }
        if (!empty($adv_id)) {
            $adv_idArr = model('Account')->where('adv_id', 'like', '%' . $adv_id . '%')->column('id');
            if (!empty($adv_idArr)) {
                $map['acc_id'] = ['in', $adv_idArr];
            } else {
                $map['acc_id'] = 0;
            }
        }

        $infos = model('Page')->getInfosByMap($map, '', false);

        foreach ($infos as $k=>$v){
            $channel = Db::name('channel')->find($v['channel_id']);
            $infos[$k]['channel_name'] = $channel['name'];
            $account = Db::name('account')->find($v['acc_id']);
            $infos[$k]['acc_name'] = $account['acc_name'];
            $infos[$k]['adv_id'] = $account['adv_id'];
            $product = Db::name('product')->find($v['pro_id']);
            $infos[$k]['pro_name'] = $product['name'];
            if($v['online_time'] != 0){
                $infos[$k]['online_time'] = date('Y-m-d H:i:s', $v['online_time']);
            }else{
                $infos[$k]['online_time'] = '';
            }
            $infos[$k]['landingpage_type'] = $this->landingpage_type_arr[$infos[$k]['landingpage_type']];
        }

        $products = model('Product')->getListByMap();
        $channels = model('Channel')->getListByMap();

        return $this->fetch('',[
            'infos' => $infos,
            'products' => $products,
            'channels' => $channels,
            'pro_name' => $pro_name,
            'accounts' => $Account,
            'group_id'=>$this->group_id,
            'ac_name' => $ac_name,
            'adv_id' => $adv_id,
        ]);
    }

    public function add(){
        if(request()->isAjax()){
//            try{

                $save_data = input('post.');

                if(empty($save_data['acc_id'])){
                    return self::showReturnCode(1011,'请选择关联账号');
                }
                $account = Db::name('account')->where('id',$save_data['acc_id'])->find();
                $save_data['channel_id']=$account['channel_id'];

                if(empty($save_data['online_url'])){
                    return self::showReturnCode(1011,'落地页链接不能为空');
                }

                if($save_data['pro_id'] == 0){
                    return self::showReturnCode(1011,'请选择关联产品');
                }

                //自建站落地页
                if ($save_data['landingpage_type'] == 1) {
                    if (empty($save_data['page_id'])) {
                        return self::showReturnCode(1011, '落地页ID不能为空');
                    } else {
                        $page = Db::name('page')->where('page_id', $save_data['page_id'])->find();
                        if (!empty($page)) {
                            return self::showReturnCode(1011, '落地页ID已存在');
                        }
                    }
                }

                //自开发落地页
                if ($save_data['landingpage_type'] == 2) {
                    if(empty($account['acc_desc'])){
                        return self::showReturnCode(1011,'自开发落地页 账号简称不能为空,需要用作短信签名');
                    }

                    if ($save_data['channel_type'] == 3 && empty($account['ocpc_token'])) { // 回传线索媒体 为百度时判断账号的token是否为空
                        return self::showReturnCode(1011,'回传媒体为百度   账号转化Token  不能为空');
                    }
                }

                $save_data['sms_signname'] = $account['acc_desc'];
                $save_data['admin_id']=session('uid');
                $save_data['online_time']=time();

                $result = $this->editData(false,'','Page',$save_data);

                if ($save_data['landingpage_type'] == 2) {
                    $save_data['online_url']=$save_data['online_url'].'?page_id='.$save_data['page_id'];
                    $result = $this->editData(false,'','Page',$save_data);
//                    $insert_id = db('page')->getLastInsID();
//                    \db('page')->where('id', $insert_id)->update(['online_url' => $save_data['online_url'] . "?landingpage_id=" . $insert_id]);
                }else{
//                    $result = $this->editData(false,'','Page',$save_data);
                }
                if($result['code'] == 1001){
                    $result['msg'] = '新增成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'落地页新增成功');
                }

                return $result;
//            }catch (\Exception $e){
//                Log::error($e->getMessage());
//                return self::showReturnCode(1011,$e->getMessage());
//            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function save()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id');
                if(!$id){
                    return self::showReturnCode(1011,'id 错误');
                }
                $save_data = input('post.');

                if($save_data['pro_id'] == 0){
                    return self::showReturnCode(1011,'请选择关联产品');
                }

                $result = $this->editData(false,'','Page',$save_data);
                if($result['code'] == 1001){
                    $result['msg'] = '关联产品成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'落地页【'.$id.'】关联产品成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function edit()
    {
        $id = input('id');
        if(!$id) return self::showReturnCode(1002,'id 错误');
        $info = model('Page')->getInfoByMap(['id'=>$id]);
        return self::showJsonReturnCodeData('1001',$info,'');
    }

    /**
     * 同步落地页
     */
    public function syn_page()
    {

        if(request()->isAjax()){

                $channel_id = input('channel_id');
                $accounts = model('Account')->getListByMap(['channel_id'=>$channel_id,'admin_id'=>$this->uid]);

                if($accounts){
                    if($channel_id == 1){
                        foreach ($accounts as $v){
                            //获取通过API创建的落地页
                            $res = (new BaiduService())->getPageList($v);
                            $list = $res[0]['list'] ?? [];
                            if(!empty($list)){
                                foreach ($list as $v2){
                                    $page = Db::name('page')->where(['page_id'=>$v2['pageId']])->find();
                                    if(!$page){
                                        $save_data['channel_id'] = $channel_id;
                                        $save_data['acc_id'] = $v['id'];
                                        $save_data['admin_id'] = $this->uid;
                                        $save_data['page_id'] = $v2['pageId'];
                                        $save_data['page_name'] = $v2['pageName'];
                                        $save_data['online_url'] = $v2['onlineUrl'];
                                        $save_data['online_time'] = strtotime($v2['createTime']);
                                        model('Page')->isUpdate(false)->data($save_data, true)->save($save_data);
                                        $this->RecordSystemLog($this->uid,$this->behavior,'同步百度落地页【'.$v2['pageName'].'】成功');
                                    }
                                }
                            }else{
                                $this->RecordSystemLog($this->uid,$this->behavior,'百度账号【'.$v['acc_name'].'】下无落地页');
                            }
                            //查询基木鱼落地页1是搜索推广, 2是信息流推广
                            $list = (new BaiduService())->getPromotionUrls($v, 1);
                            if(!empty($list)){
                                foreach ($list as $v2){
                                    $page = Db::name('page')->where(['page_id'=>$v2['pageId']])->find();
                                    if(!$page){
                                        $save_data['channel_id'] = $channel_id;
                                        $save_data['acc_id'] = $v['id'];
                                        $save_data['admin_id'] = $this->uid;
                                        $save_data['page_id'] = $v2['pageId'];
                                        $save_data['page_name'] = $v2['pageName'];
                                        $save_data['online_url'] = $v2['onlineUrl'];
                                        $save_data['online_time'] = 0;
                                        model('Page')->isUpdate(false)->data($save_data, true)->save($save_data);
                                        $this->RecordSystemLog($this->uid,$this->behavior,'同步百度落地页【'.$v2['pageName'].'】成功');
                                    }
                                }
                            }else{
                                $this->RecordSystemLog($this->uid,$this->behavior,'百度账号【'.$v['acc_name'].'】下无落地页');
                            }

                            //查询基木鱼落地页1是搜索推广, 2是信息流推广
                            $list = (new BaiduService())->getPromotionUrls($v, 2);
                            if(!empty($list)){
                                foreach ($list as $v2){
                                    $page = Db::name('page')->where(['page_id'=>$v2['pageId']])->find();
                                    if(!$page){
                                        $save_data['channel_id'] = $channel_id;
                                        $save_data['acc_id'] = $v['id'];
                                        $save_data['admin_id'] = $this->uid;
                                        $save_data['page_id'] = $v2['pageId'];
                                        $save_data['page_name'] = $v2['pageName'];
                                        $save_data['online_url'] = $v2['onlineUrl'];
                                        $save_data['online_time'] = 0;
                                        model('Page')->isUpdate(false)->data($save_data, true)->save($save_data);
                                        $this->RecordSystemLog($this->uid,$this->behavior,'同步百度落地页【'.$v2['pageName'].'】成功');
                                    }
                                }
                            }else{
                                $this->RecordSystemLog($this->uid,$this->behavior,'百度账号【'.$v['acc_name'].'】下无落地页');
                            }
                        }
                    }elseif($channel_id == 2){
                        foreach ($accounts as $v){
                            $list = (new TengxunService())->getPageList($v);
                            if(!empty($list)){
                                foreach ($list as $v2){
                                    $page = Db::name('page')->where(['online_url'=>$v2['preview_url']])->find();
                                    if(!$page){
                                        $save_data['channel_id'] = $channel_id;
                                        $save_data['acc_id'] = $v['id'];
                                        $save_data['admin_id'] = $this->uid;
                                        $save_data['page_id'] = $v2['page_id'];
                                        $save_data['page_name'] = $v2['page_name'];
                                        $save_data['online_url'] = $v2['preview_url'];
                                        $save_data['online_time'] = $v2['created_time'];
                                        model('Page')->isUpdate(false)->data($save_data, true)->save($save_data);
                                        $this->RecordSystemLog($this->uid,$this->behavior,'同步腾讯落地页【'.$v2['preview_url'].'】成功');
                                    }
                                    if(strpos($v2['preview_url'],'h5.gdt.qq.com') !== false){
                                        $replace_url = str_replace('h5.gdt.qq.com', 'xj.gdt.qq.com', $v2['preview_url']);
                                        $page = Db::name('page')->where(['online_url'=>$replace_url])->find();
                                        if(!$page){
                                            $save_data['channel_id'] = $channel_id;
                                            $save_data['acc_id'] = $v['id'];
                                            $save_data['admin_id'] = $this->uid;
                                            $save_data['page_id'] = $v2['page_id'];
                                            $save_data['page_name'] = $v2['page_name'];
                                            $save_data['online_url'] = $replace_url;
                                            $save_data['online_time'] = $v2['created_time'];
                                            model('Page')->isUpdate(false)->data($save_data, true)->save($save_data);
                                            $this->RecordSystemLog($this->uid,$this->behavior,'同步腾讯落地页【'.$replace_url.'】成功');
                                        }
                                    }

                                }
                            }else{
                                $this->RecordSystemLog($this->uid,$this->behavior,'腾讯账号【'.$v['acc_name'].'】下无落地页');
                            }
                        }
                    }elseif($channel_id == 3){
                        foreach ($accounts as $v){
                            // 获取橙子建站站点详细信息
                            $list = (new JuliangService())->getSiteData($v);
                            if(!empty($list)){
                                foreach ($list as $v2){
                                    $page = Db::name('page')->where(['page_id'=>$v2['siteId']])->find();
                                    if(!$page){
                                        $save_data['channel_id'] = $channel_id;
                                        $save_data['acc_id'] = $v['id'];
                                        $save_data['admin_id'] = $this->uid;
                                        $save_data['page_id'] = $v2['siteId'];
                                        $save_data['page_name'] = $v2['name'];
                                        $save_data['online_url'] = str_replace(substr($v2['url'], strpos($v2['url'],"&q=")), '', $v2['url']);
                                        $save_data['online_time'] = 0;
                                        model('Page')->isUpdate(false)->data($save_data, true)->save($save_data);
                                        $this->RecordSystemLog($this->uid,$this->behavior,'同步巨量橙子建站落地页【'.$v2['name'].'】成功');
                                    }
                                }
                            }else{
                                $this->RecordSystemLog($this->uid,$this->behavior,'巨量账号【'.$v['acc_name'].'】下无橙子建站落地页');
                            }
                            // 获取第三方落地页站点列表
                            $list = (new JuliangService())->getThirdSiteData($v);
                            if(!empty($list)){
                                foreach ($list as $v2){
                                    $page = Db::name('page')->where(['page_id'=>$v2['site_id']])->find();
                                    if(!$page){
                                        $save_data['channel_id'] = $channel_id;
                                        $save_data['acc_id'] = $v['id'];
                                        $save_data['admin_id'] = $this->uid;
                                        $save_data['page_id'] = $v2['site_id'];
                                        $save_data['page_name'] = $v2['name'];
                                        $save_data['online_url'] = $v2['url'];
                                        $save_data['online_time'] = strtotime($v2['create_time']);
                                        model('Page')->isUpdate(false)->data($save_data, true)->save($save_data);
                                        $this->RecordSystemLog($this->uid,$this->behavior,'同步巨量第三方落地页【'.$v2['name'].'】成功');
                                    }
                                }
                            }else{
                                $this->RecordSystemLog($this->uid,$this->behavior,'巨量账号【'.$v['acc_name'].'】下无第三方落地页');
                            }
                        }
                    }else{
                        return self::showReturnCode(1002,'该媒体渠道不支持同步落地页');
                    }


                    $result['code'] = 1001;
                    $result['msg'] = '同步落地页成功';
                    return $result;

                }else{
                    return self::showReturnCode(1002,'运营下无媒体渠道账户');
                }

        }else{
            return self::showReturnCode(1002);
        }



    }

}